import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';





class FormIndex extends StatefulWidget {
  const FormIndex({Key? key,  this.title="form"}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<FormIndex> createState() => _FormIndexState();
}

class _FormIndexState extends State<FormIndex> {
  int _counter = 0;

  final _formKey = GlobalKey();
  String? name = "", password = "", mobile = "";

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  bool _hasSubmited = false;
  ValueNotifier<bool> _submitting = ValueNotifier<bool>(false);

  FToast fToast = FToast();

  @override
  void initState() {
    super.initState();
    fToast.init(context);
    _submitting.addListener(() {
      print('_submitting.value：${_submitting.value}');
      setState(() {
        if (_submitting.value == false) {
          _showToast('提交成功');
        }
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _submitting.dispose();
  }

  _showToast(String msg) {
    Widget toast = Container(
      padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(25.0),
        color: Colors.greenAccent,
      ),
      child: Row(
        mainAxisSize: MainAxisSize.min,
        children: [
          Icon(Icons.check),
          SizedBox(
            width: 12.0,
          ),
          Text(msg),
        ],
      ),
    );
    fToast.showToast(
      child: toast,
      gravity: ToastGravity.BOTTOM,
      toastDuration: Duration(seconds: 2),
    );
    // Custom Toast Position
    // fToast.showToast(
    //     child: toast,
    //     toastDuration: Duration(seconds: 2),
    //     positionedToastBuilder: (context, child) {
    //       return Positioned(
    //         child: child,
    //         top: 16.0,
    //         left: 16.0,
    //       );
    //     });
  }

  _submit() async {
    _submitting.value = true;
    await Future.delayed(Duration(seconds: 2));
    _submitting.value = false;
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: SafeArea(
        child: Padding(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
          child: SingleChildScrollView(
            child: Column(
              children: [
                Text('name:${name}'),
                Text('mobile:${mobile}'),
                Text('password:${password}'),
                Form(
                  autovalidateMode: _hasSubmited
                      ? AutovalidateMode.always
                      : AutovalidateMode.disabled,
                  key: _formKey,
                  onChanged: () {
                    print('form changed');
                    (_formKey.currentState as FormState).save();
                  },
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      TextFormField(
                        // autovalidateMode: AutovalidateMode.always,
                        decoration: InputDecoration(

                          hintText: "Please input name",
                          prefixIcon: Icon(Icons.person),
                          labelText: 'name',
                          hintStyle:
                          TextStyle(color: Colors.red, fontSize: 13.0),
                          // 未获得焦点下划线设为灰色
                          enabledBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.blue),
                          ),
                          //获得焦点下划线设为蓝色
                          focusedBorder: UnderlineInputBorder(
                            borderSide: BorderSide(color: Colors.red),
                          ),
                        ),

                        onSaved: (value) {
                          setState(() {
                            name = value;
                          });
                        },

                        // 校验用户名
                        validator: (v) {
                          return v!.trim().length > 0 ? null : "用户名不能为空";
                        },
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      TextFormField(
                        keyboardType: TextInputType.number,
                        decoration: InputDecoration(
                          helperText: '',
                          hintText: "Please input mobile",
                          prefixIcon: Icon(Icons.call),
                          labelText: 'mobile',
                        ),
                        onSaved: (value) {
                          setState(() {
                            mobile = value;
                          });
                        },
                        validator: (v) {
                          return v!.trim().length > 0 ? null : '手机号不能为空';
                        },
                      ),
                      SizedBox(
                        height: 20,
                      ),
                      TextFormField(
                        obscureText: true,
                        decoration: InputDecoration(
                            hintText: "Please input password",
                            prefixIcon: Icon(Icons.lock),
                            labelText: 'password',
                            border: OutlineInputBorder(
                                borderSide: BorderSide(color: Colors.blue))),
                        onSaved: (value) {
                          setState(() {
                            password = value;
                          });
                        },
                        //校验密码
                        validator: (v) {
                          return v!.trim().length > 5 ? null : "密码不能少于6位";
                        },
                      ),
                      SizedBox(height: 30),
                      Container(
                        constraints: BoxConstraints(
                            minWidth: double.infinity, minHeight: 50),
                        child: ElevatedButton(
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              ValueListenableBuilder(
                                valueListenable: _submitting,
                                builder: (BuildContext context, value,
                                    Widget? child) {
                                  return value == true
                                      ? CircularProgressIndicator(
                                    backgroundColor: Colors.grey[200],
                                    valueColor: AlwaysStoppedAnimation(
                                        Colors.blue),
                                  )
                                      : Container();
                                },
                              ),
                              SizedBox(width: _submitting.value ? 20 : 0),
                              Text('submit${_submitting.value ? '...' : ''}')
                            ],
                          ),
                          onPressed: () {
                            if (!_hasSubmited) {
                              setState(() {
                                _hasSubmited = true;
                              });
                            }
                            (_formKey.currentState as FormState).save();
                            // 通过后再提交数据。
                            if ((_formKey.currentState as FormState)
                                .validate()) {
                              //验证通过提交数据
                              print('数据填写正确');
                              _submit();
                            }
                          },
                        ),
                      ),
                      SizedBox(height: 30),
                      Container(
                        constraints: BoxConstraints(
                            minWidth: double.infinity, minHeight: 50),
                        child: ElevatedButton(
                          child: Text('reset'),
                          onPressed: () {
                            (_formKey.currentState as FormState).reset();
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
